/*
 *    This file is part of CeluMap.
 *
 *    CeluMap is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU Lesser General Public License as published by
 *    the Free Software Foundation; either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    CeluMap is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *    Copyright 2006, 2007, 2008 Gonzalo Merayo
 *    gonzalo (at) celumap.com.ar
 *    www.celumap.com.ar
 *
 */

package map.file.layer;

import figures.FigureIterator;
import file.FileGetter;
import geometry.MovingTransform;
import geometry.Rectangle;

import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;

import map.CachedMap;
import map.Map;
import map.file.CachedIndexMap;
import map.file.CombinationMap;
import map.file.FileMap;

public class LayerMap implements CachedMap {
	private CachedMap map;
	private long zoomUpperLimit;
	private long zoomLowerLimit;
	private MovingTransform transform;
	LayerMap(CachedMap m, long up, long low, MovingTransform t){
		map = m;
		zoomUpperLimit = up;
		zoomLowerLimit = low;
		transform = t;
	}
	public FigureIterator getFigures(Rectangle area) {
		if(transform.getZoom() >= zoomLowerLimit && transform.getZoom() <= zoomUpperLimit)
			return map.getFigures(area);
		unload();
		return null;
	}
	
	public static Map loadLayers(FileGetter g,String s, MovingTransform t){
		CombinationMap layerManager = new CombinationMap();
		try {
			InputStream st = g.getResource(s);
			DataInputStream is = new DataInputStream(st);
			Rectangle area = new Rectangle();
			area.load(is);
			is.readShort();
			layerManager.setArea(area);
			while(true)
				layerManager.appendMap(loadMap(g, is, t));
		} catch (EOFException e) {
//			eof
		} catch (IOException e) {
			e.printStackTrace();
		}
		return layerManager;
	}
	
	public static LayerMap loadMap(FileGetter g,DataInputStream is, MovingTransform transform) throws IOException{
		long low = is.readLong();
		long up =is.readLong(); 
		String map = FileMap.readString(is);//archivo mapa
		return new LayerMap(new CachedIndexMap(g, map, null), up, low, transform);
	}
	public void unload() {
		map.unload();
	}
}
